package com.channel.connector.ctripos.controller;

import com.channel.connector.ctripos.common.constant.CtripOSCommonConstants;
import com.channel.connector.ctripos.service.OrderSyncService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

/**
 * 对外提供给携程调用
 */
@Controller
@Slf4j
@RequestMapping("/ctripos")
public class OrderController {

    @Autowired
    private OrderSyncService orderSyncService;

    private static final String SOAP_IF_HEADER = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"> <SOAP-ENV:Header/> <SOAP-ENV:Body>";
    private static final String SOAP_IF_TAIL = "</SOAP-ENV:Body></SOAP-ENV:Envelope>";

    @RequestMapping(value = "/order", method = RequestMethod.POST, produces = {"application/xml;charset=UTF-8"})
    public void handleOrder(HttpServletRequest request, HttpServletResponse response) {
        //读取携程post过来的请求串
        String xmlReq;
        SAXReader reader = new SAXReader();
        Document document = null;
        String requestType = null;
        try {
            document = reader.read(request.getInputStream());
            Element root = document.getRootElement();
            xmlReq = document.asXML();
            Element rqElement = null;
            Element bodyElement = root.element("Body");
            if (xmlReq.contains(CtripOSCommonConstants.OTA_HotelAvailRQ)) {
                rqElement = bodyElement.element(CtripOSCommonConstants.OTA_HotelAvailRQ);
                requestType = CtripOSCommonConstants.OTA_HotelAvailRQ;
            } else if (xmlReq.contains(CtripOSCommonConstants.OTA_HotelResRQ)) {
                rqElement = bodyElement.element(CtripOSCommonConstants.OTA_HotelResRQ);
                requestType = CtripOSCommonConstants.OTA_HotelResRQ;
            } else if (xmlReq.contains(CtripOSCommonConstants.OTA_CancelRQ)) {
                rqElement = bodyElement.element(CtripOSCommonConstants.OTA_CancelRQ);
                requestType = CtripOSCommonConstants.OTA_CancelRQ;
            } else if (xmlReq.contains(CtripOSCommonConstants.OTA_ReadRQ)) {
                rqElement = bodyElement.element(CtripOSCommonConstants.OTA_ReadRQ);
                requestType = CtripOSCommonConstants.OTA_ReadRQ;
            }
            xmlReq = rqElement == null ? null : rqElement.asXML();
        } catch (Exception e) {
            log.error("解析请求xml失败, document=" + ((null != document) ? document.asXML() : null), e);
            return;
        }

        try {
            if (StringUtils.isNotEmpty(xmlReq) && !xmlReq.startsWith("<")) {
                log.error("OrderOperate request format error, xmlReq=" + xmlReq);
                xmlReq = URLDecoder.decode(xmlReq, "utf-8");
            }
            String xmlRes = orderSyncService.orderRequestEntry(xmlReq, requestType);
            xmlRes = SOAP_IF_HEADER + xmlRes + SOAP_IF_TAIL;
            byte[] xmlData = xmlRes.getBytes("utf-8");
            response.setContentType("text/xml; charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentLength(xmlData.length);

            ServletOutputStream os = response.getOutputStream();
            os.write(xmlData);
            os.flush();
            os.close();
        } catch (Exception e) {
            log.error("处理订单操作异常", e);
        }
    }
}
